<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container" style="float: right">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入角色名称"/>
      <el-button v-permission="['GET /admin/role/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/role/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>
      <el-table-column align="center" label="角色名称" prop="name" sortable/>

      <el-table-column align="center" label="角色描述" prop="desc"/>

      <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/role/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/role/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          <el-button v-permission="['GET /admin/role/permissions']" type="primary" size="mini" @click="handlePermission(scope.row)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="roleForm" :rules="rules" :model="roleForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="roleForm.desc"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createRole">确定</el-button>
        <el-button v-else type="primary" @click="updateRole">确定</el-button>
      </div>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog :visible.sync="permissionDialogFormVisible" title="权限配置">
      <el-tree
        ref="tree"
        :data="systemPermissions"
        :default-checked-keys="assignedPermissions"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        highlight-current>
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ data.label }}</span>&nbsp;&nbsp;
          <el-tag v-if="data.api" type="success" size="mini">{{ data.api }}</el-tag>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermission">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listRole, createRole, updateRole, deleteRole, getPermission, updatePermission } from '@/api/system/role'
import Pagination from '@/components/Pagination'
export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      list: [], // 角色列表
      total: 0, // 数据总量
      listLoading: true,
      // element-admin 分页
      listQuery: {
        page: 1,
        limit: 20,
        /* name: undefined,
        sort: 'createTime',
        order: 'desc' */
      },
      // 角色表单数据
      roleForm: {
        id: undefined,
        name: undefined,
        desc: undefined
      },
      // 角色模态框启用状态
      dialogFormVisible: false,
      // 角色模态框类型 创建or编辑
      dialogStatus: '',
      // 角色模态框标题
      textMap: {
        update: '编辑',
        create: '创建'
      },
      // 验证规则
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 权限配置模态框
      permissionDialogFormVisible: false,
      systemPermissions: null, // 权限数据
      assignedPermissions: null, // 勾选节点的数组
      // 权限表单数据
      permissionForm: {
        roleId: undefined,
        permissions: []
      }
    }
  },
  created() {
    // 角色列表初始化
    this.getList()
  },
  methods: {
    // 获取角色列表信息
    getList() {
      this.listLoading = true
      listRole(this.listQuery)
        .then(response => {

          this.list = response.data.data
          this.total = response.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 查询按钮钩子
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 重置角色表单数据
    resetForm() {
      this.roleForm = {
        id: undefined,
        name: undefined,
        desc: undefined
      }
    },
    // 新增角色按钮
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['roleForm'].clearValidate()
      })
    },
    // 确认新增角色
    createRole() {
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          createRole(this.roleForm)
            .then(response => {
              this.list.unshift(response.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加角色成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 编辑角色按钮
    handleUpdate(row) {
      this.roleForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['roleForm'].clearValidate()
      })
    },
    // 确认编辑角色
    updateRole() {
      this.$refs['roleForm'].validate(valid => {
        if (valid) {
          updateRole(this.roleForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.roleForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.roleForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新角色成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    // 删除角色
    handleDelete(row) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除角色成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 获取权限信息
    handlePermission(row) {
      this.permissionDialogFormVisible = true
      this.permissionForm.roleId = row.id
      getPermission({ roleId: row.id })
        .then(response => {
          console.log("-------getPermission:%o",response);
          this.systemPermissions = response.data.systemPermissions
          this.assignedPermissions = response.data.assignedPermissions
        })
    },
    // 更新权限
    updatePermission() {
      this.permissionForm.permissions = this.$refs.tree.getCheckedKeys(true)
      updatePermission(this.permissionForm)
        .then(response => {
          this.permissionDialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '授权成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    }
  }
}
</script>

